<script setup lang="ts">
import { useGetPricingProjectOptions, useGetProductDetail, usePublishProduct, useSetPricingProjectForProduct } from '@fl/api/purchase'
import SubmitBtn from '@fl/components/submit-btn.vue'

import { PRICING_PRODUCT_STATUS_MAP } from '../goods-management/constant'
import CalculateRules from './calculate-rules.vue'
import PublishError from './components/publish-error.vue'
import GeneralDescription from './general-description.vue'
import PricingList from './pricing-list.vue'
import Statement from './statement.vue'

const route = useRoute()
const router = useRouter()

const showPublishError = ref<boolean>(false)
const errorData = ref<any>({})
const projectId = ref<string>()

const getPricingProjectOptionsParams = computed(() => productDetailData.value?.categoryId)

const { data: productDetailData, isLoading: isGetProductDetailLoading } = useGetProductDetail(route.query.id as string)
const { isPending: _isPublishProductPending, mutate: publishProduct } = usePublishProduct()
const { data: pricingProjectOptionsData, isLoading: _isGetPricingProjectOptionsLoading } = useGetPricingProjectOptions(getPricingProjectOptionsParams)
const { isPending: isSetPricingProjectForProductPending, mutate: setPricingProjectForProduct } = useSetPricingProjectForProduct()

const isSubmitLoading = computed(() => isSetPricingProjectForProductPending.value)
const isNotPublished = computed(() => productDetailData.value?.status === PRICING_PRODUCT_STATUS_MAP.NOT_PUBLISHED)

const childRefs = ref([])
const tabsData = [
    {
        component: GeneralDescription,
        label: '编制总说明',
        name: 'generalDescription',
    },
    {
        component: CalculateRules,
        label: '计算规则',
        name: 'calculateRules',
    },
    {
        component: PricingList,
        label: '组价清单',
        name: 'pricingList',
    },
    {
        component: Statement,
        label: '报表',
        name: 'statement',
    },
]
const activeName = ref(route.query.activeName as string || 'generalDescription')

// #region UI Listener
function onTabChange(name: string) {
    if (name === 'statement') {
        const componentRef = childRefs.value[3] as any
        componentRef.refetchPricingReportList()
        nextTick(() => {
            componentRef.expandTable()
        })
    }
}

function handlePublish(_name: string) {
    // for (const child of childRefs.value) {
    //     console.log((child as any).data)
    // }
    publishProduct(productDetailData.value.productId, {
        onSuccess(data: any) {
            if (data.code === 200) {
                ElMessage.success('操作成功')
                router.back()
            }
            else if (data.code === 500) {
                showPublishError.value = true
                errorData.value = data.data || { msg: data.msg }
            }
            else {
                ElMessage.error('操作失败')
            }
        },
    })
}

function onSetPricingProjectBtnClick() {
    const params = {
        productId: productDetailData.value.productId,
        projectId: projectId.value,
    }
    setPricingProjectForProduct(params, {
        onSuccess(data) {
            console.log(data)
            ElMessage.success('操作成功')
        },
    })
}
// #endregion

watchEffect(() => {
    projectId.value = productDetailData.value?.priceProId
})
</script>

<template>
    <el-skeleton v-if="isGetProductDetailLoading"
                 animated
    />

    <el-tabs v-else
             v-model="activeName"
             class="h-[calc(100vh-162px)]"
             @tab-change="onTabChange"
    >
        <el-tab-pane v-for="(item) in tabsData"
                     :key="item.name"
                     :label="item.label"
                     :name="item.name"
                     class="h-full overflow-x-hidden overflow-y-auto"
        >
            <component :is="item.component"
                       ref="childRefs"
                       :detail-data="productDetailData"
                       @publish="handlePublish(item.name)"
            />
        </el-tab-pane>
    </el-tabs>

    <div class="flex absolute w-[30%] justify-end right-20 top-20">
        <el-select v-model="projectId"
                   placeholder="请选择价格库"
                   clearable
        >
            <el-option v-for="item in pricingProjectOptionsData"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
            />
        </el-select>

        <SubmitBtn v-if="isNotPublished"
                   type="primary"
                   class="ml-16"
                   :loading="isSubmitLoading"
                   @click="onSetPricingProjectBtnClick"
        >
            使用价格库
        </SubmitBtn>
    </div>

    <PublishError v-model:visible="showPublishError"
                  :error-data="errorData"
    />
</template>

<style scoped lang="scss">
:deep(.el-tabs__content) {
    height: calc(100% - 55px);
}
</style>
